#include "ShareMemAPI.h"

#include <stdio.h>

namespace ShareMemAPI
{


sm_handle		CreateShareMem(sm_key key,uint Size)
{
#if __LINUX__
	//key = ftok(keybuf,'w'); 
	sm_handle hd =  shmget(key ,Size,IPC_CREAT|IPC_EXCL|0666); 
	printf("handle = %d ,key = %d ,error: %d \r\n",hd,key,errno);
	return hd;
#elif __WINDOWS__
	char keybuf[64];
	memset(keybuf,0,64);
	sprintf(keybuf,"%d",key);
	return  CreateFileMappingA( (HANDLE)0xFFFFFFFFFFFFFFFF, NULL, PAGE_READWRITE, 0, Size, keybuf );
#endif
	return sm_handle(-1);
}

sm_handle		OpenShareMem(sm_key key,uint Size)
{
#if __LINUX__
	//key = ftok(keybuf,'w'); 
	sm_handle hd =   shmget(key , Size,0);
	printf("handle = %d ,key = %d ,error: %d \r\n",hd,key,errno);
	return hd;
#elif __WINDOWS__
	char keybuf[64];
	memset(keybuf,0,64);
	sprintf(keybuf,"%d",key);
	return OpenFileMappingA( FILE_MAP_ALL_ACCESS, true, keybuf);
#endif
	return sm_handle(-1);
}

char*			MapShareMem(sm_handle handle)
{
#if __LINUX__
	return  (char*)shmat(handle,0,0);
#elif __WINDOWS__
	return (char *)MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, 0);
#endif
	return 0;

}


void			UnMapShareMem(char* MemoryPtr)
{
#if __LINUX__
	  shmdt(MemoryPtr);
#elif __WINDOWS__
	 UnmapViewOfFile(MemoryPtr);
#endif
}


void			CloseShareMem(sm_handle handle)
{
#if __LINUX__
	shmctl(handle,IPC_RMID,0); 
#elif __WINDOWS__
	CloseHandle(handle);
#endif
}

}